package cn.cvs.controller;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.sysUser.SysRoleService;
import cn.cvs.service.sysUser.SysUserService;
import cn.cvs.test.Constants;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger  logger = Logger.getLogger(SysUserController.class);
    @Resource
    private SysUserService  sysUserService;
    private SysRoleService sysRoleService;
    @RequestMapping("/toLogin")
    public String login(){
        logger.info("跳转到登录页面");
        return "login";
    }
    @RequestMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password){
        logger.info("登录方法");
        SysUser sysUser = sysUserService.login(account,password);
        if (null!=sysUser){
            session.setAttribute("currentUser",sysUser);
            //登录成功。重定向到user/toMain接口
            return "redirect:/user/toMain";
        }else {
            request.setAttribute("error","用户名或密码错误");
            //登录失败。返回登录页面。
            return "login";
        }
    }
    @RequestMapping("/toMain")
    public String toMain(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION)==null){
            return "redirect:/user/login";//重定向到登录页面。
        }
        return "frame";
    }

    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest req){
        req.setAttribute("e",e);
        return "error";//跳转到error页面。
    }

    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account,@RequestParam String password){
        SysUser user = sysUserService.login(account,password);
        if (user==null){
            throw new RuntimeException("用户名或密码错误");
        }
        return "redirect";
    }
    public String getUserList(Model model,String realName,Integer roleId,@RequestParam(defaultValue = "1")Integer pageIndex){
        SysUser sysUser = new SysUser();
        sysUser.setRoleId(roleId);
        sysUser.setRealName(realName);
        // 页面大小
        Integer pageSize = 5;

        List<SysUser> list = sysUserService.selectSysUserList(sysUser, pageIndex, pageSize);
        model.addAttribute("userList", list);

        List<SysRole> roleList = sysRoleService.getRoleList();
        model.addAttribute("roleList", roleList);

        model.addAttribute("roleId", roleId);
        model.addAttribute("realName", realName);


//        totalCount 总记录数
        Integer totalCount = sysUserService.selectCount(sysUser);

        //totalPageCount 总页数
        Integer totalPageCount = totalCount / pageSize;
        if (totalCount % pageSize != 0) {
            totalPageCount++;
        }

        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);

//        currentPageNo 当前页码
        model.addAttribute("currentPageNo", pageIndex);

        return "/sysUser/list";
    }
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";//跳转到error页面。
    }

    @GetMapping("/add")
    public String toAdd(@ModelAttribute("sysUser")SysUser sysUser){
        return "sysUser/add";//跳转到error页面。
    }
    @PostMapping("/add")
    public String add(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session){
        if (bindingResult.hasErrors()){
            logger.debug("添加用户信息验证失败");
            return "sysUser/add";//跳转到error页面。
        }
        sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.add(sysUser)>0){
            return "redirect:/user/getUserList";
        }
        return "sysUser/add";//跳转到error页面。

    }

    @ResponseBody
//    @GetMapping(value = "/view/{id}",produces = {"application/json;charset=UTF-8"})
    @GetMapping(value = "/view/{id}")
    public Object view (@PathVariable String id,Model model){
        logger.debug("根据id查询用户详情"+id);
        SysUser sysUser = null;
        try{
            sysUser = sysUserService.getUserById(id);
            logger.debug("查询到的用户信息"+sysUser);
        }catch (Exception e){
            e.printStackTrace();
            return "failed";
        }
        return sysUser;

    }
    @GetMapping("/toUpdate")
    public String toUpdate(@RequestParam String uid,Model model){
        logger.debug("跳转到修改用户信息页面");
        SysUser sysUser = sysUserService.getUserById(uid);
        model.addAttribute(sysUser);
        return "sysUser/update";//跳转到error页面。
    }
    @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam String account){
        logger.debug("验证用户名account="+account+"的用户是否存在");
        HashMap<String,Object> resultMap = new HashMap<String,Object>();
        if(StringUtils.isNullOrEmpty(account)){
            resultMap.put("exist",1);
        }else {
            SysUser sysUser = sysUserService.getAccountExist(account);
            if(sysUser!=null){
                resultMap.put("exist",1);
            }else {
                resultMap.put("exist",0);
            }
        }
        return JSON.toJSONString(resultMap);
    }
    @PostMapping("/update")
    public String update(SysUser sysUser,HttpSession session){
        logger.debug("修改用户信息");
        sysUser.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if(sysUserService.update(sysUser)){
            return "redirect:/user/List";
        }
        return "sysUser/update";//跳转到error页面。
    }
}
